#
#  Copyright 2022 The Open Islands Authors. All Rights Reserved.
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
#
from pyoi.constant import FederatedPacketType
from pyoi.util.base_utils import json_dumps, json_loads

from .federated_packet_properties import FederatedPacketProperties
from .federated_packet_routing import FederatedPacketRouting


class FederatedPacketHeaders:
    def __init__(self, packet_type: FederatedPacketType, routing: FederatedPacketRouting,
                 properties: FederatedPacketProperties,
                 encoding_request_content: str = "", request_content_encoding: str = "",
                 request_content_compress_level: int = 5):
        self.packet_type = packet_type
        self.routing = routing
        self.properties = properties
        self.encoding_request_content = encoding_request_content
        self.request_content_encoding = request_content_encoding
        self.request_content_compress_level = request_content_compress_level

    def to_dict(self) -> dict:
        d = {
            "packet-type": self.packet_type.name,
            "routing": json_dumps(self.routing.to_dict()),
            "properties": json_dumps(self.properties.to_dict()),
            "encoding-request-content": self.encoding_request_content,
            "request-content-encoding": self.request_content_encoding,
            "request-content-compress-level": str(self.request_content_compress_level)
        }
        return d

    @classmethod
    def from_dict(cls, d: dict):
        return FederatedPacketHeaders(
            packet_type=FederatedPacketType[d.get("packet-type", "")],
            routing=FederatedPacketRouting.from_dict(json_loads(d["routing"])),
            properties=FederatedPacketProperties.from_dict(json_loads(d["properties"])),
            encoding_request_content=d.get("encoding-request-content", ""),
            request_content_encoding=d.get("request-content-encoding", ""),
            request_content_compress_level=int(d.get("request-content-compress-level", 5))
        )
